A WeakMap is a collection in JavaScript that allows you to store key-value pairs where the keys are weakly held, meaning they don't prevent the garbage collection of their associated values. This is useful for scenarios where you want to associate data with objects without preventing their disposal.
In a regular Map, as long as the Map exists, the objects used as keys will stay in memory—even if you delete every other reference to that object. This can lead to memory leaks.
In a WeakMap, if there are no other references to the key object anywhere else in your code, the JavaScript engine's Garbage Collector is allowed to remove that object from memory and delete the corresponding entry in the WeakMap automatically.
Keys must be Objects: Unlike a regular Map (which can use strings or numbers as keys), a WeakMap only accepts objects (and registered symbols) as keys.
Not Iterable: You cannot loop through a WeakMap. There is no .forEach(), .keys(), or .size property.